package com.leon.datalink.core.persistence;

import com.leon.datalink.core.persistence.event.*;
import com.leon.datalink.core.persistence.state.NodeState;
import com.leon.datalink.core.persistence.state.NodeStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 第四阶段批量验证程序
 * 
 * 验证所有节点Actor类型的持久化功能：
 * 1. 智能快照策略验证
 * 2. 性能监控指标验证
 * 3. 状态恢复正确性验证
 * 4. 不同Actor类型的持久化策略验证
 * 5. 系统级别的性能统计验证
 * 
 * @author leon
 */
public class Phase4BatchVerification {
    
    private static final Logger logger = LoggerFactory.getLogger(Phase4BatchVerification.class);
    
    public static void main(String[] args) {
        logger.info("=== DataLink Actor持久化功能第四阶段批量验证 ===");
        
        try {
            Phase4BatchVerification verification = new Phase4BatchVerification();
            verification.runBatchVerification();
            
            logger.info("=== 第四阶段批量验证完成 ===");
            
        } catch (Exception e) {
            logger.error("第四阶段批量验证失败", e);
            System.exit(1);
        }
    }
    
    public void runBatchVerification() throws Exception {
        logger.info("开始第四阶段批量验证...");
        
        // 1. 验证智能快照策略管理器
        verifySnapshotStrategyManager();
        
        // 2. 验证性能监控管理器
        verifyPersistenceMetricsManager();
        
        // 3. 验证不同Actor类型的持久化策略
        verifyActorTypePersistenceStrategies();
        
        // 4. 验证状态变化统计
        verifyStateChangeStatistics();
        
        // 5. 验证性能监控和报告
        verifyPerformanceMonitoring();
        
        // 6. 验证系统级别的聚合指标
        verifySystemLevelMetrics();
        
        logger.info("第四阶段批量验证全部通过！");
    }
    
    /**
     * 验证智能快照策略管理器
     */
    private void verifySnapshotStrategyManager() {
        logger.info("验证智能快照策略管理器...");
        
        SnapshotStrategyManager manager = SnapshotStrategyManager.getInstance();
        
        // 测试不同Actor类型的快照策略
        String[] actorTypes = {
            "com.leon.datalink.rule.actor.RuleActor",
            "com.leon.datalink.rule.actor.ScheduleNodeActor", 
            "com.leon.datalink.rule.actor.DriverNodeActor",
            "com.leon.datalink.rule.actor.SpeedNodeActor",
            "com.leon.datalink.rule.actor.PackNodeActor"
        };
        
        for (String actorType : actorTypes) {
            String nodeId = "test-node-" + actorType.substring(actorType.lastIndexOf('.') + 1);
            
            // 获取快照策略
            SnapshotStrategyManager.SnapshotStrategy strategy = manager.getSnapshotStrategy(actorType, nodeId);
            assert strategy != null : "快照策略不能为空";
            assert strategy.getSnapshotFrequency() > 0 : "快照频率必须大于0";
            assert strategy.getMaxSnapshots() > 0 : "最大快照数必须大于0";
            assert strategy.getMaxSnapshotInterval() > 0 : "最大快照间隔必须大于0";
            
            logger.debug("Actor类型 {} 的快照策略: freq={}, maxSnapshots={}, maxInterval={}ms",
                        actorType, strategy.getSnapshotFrequency(), strategy.getMaxSnapshots(), 
                        strategy.getMaxSnapshotInterval());
            
            // 测试快照判断逻辑
            NodeState testState = createTestNodeState(nodeId);
            boolean shouldSnapshot = manager.shouldCreateSnapshot(actorType, nodeId, 
                                                                strategy.getSnapshotFrequency(), testState);
            assert shouldSnapshot : "达到快照频率时应该创建快照";
            
            // 记录快照创建
            manager.recordSnapshotCreated(actorType, nodeId, 1024);
            assert strategy.getSnapshotCount() > 0 : "快照计数应该增加";
        }
        
        logger.info("✓ 智能快照策略管理器验证通过");
    }
    
    /**
     * 验证性能监控管理器
     */
    private void verifyPersistenceMetricsManager() {
        logger.info("验证性能监控管理器...");
        
        PersistenceMetricsManager manager = PersistenceMetricsManager.getInstance();
        
        // 清空之前的指标
        manager.clearMetrics();
        
        String actorType = "TestActor";
        String nodeId = "test-node-001";
        
        // 记录持久化操作
        manager.recordPersistOperation(actorType, nodeId, 50, 1024);
        manager.recordPersistOperation(actorType, nodeId, 75, 2048);
        
        // 记录恢复操作
        manager.recordRecoveryOperation(actorType, nodeId, 100, 5);
        
        // 记录快照操作
        manager.recordSnapshotOperation(actorType, nodeId, 200, 4096);
        
        // 验证Actor级别指标
        PersistenceMetricsManager.ActorMetrics actorMetrics = manager.getActorMetrics(actorType, nodeId);
        assert actorMetrics != null : "Actor指标不能为空";
        assert actorMetrics.getTotalPersistCount() == 2 : "持久化计数应该为2";
        assert actorMetrics.getTotalRecoveryCount() == 1 : "恢复计数应该为1";
        assert actorMetrics.getTotalSnapshotCount() == 1 : "快照计数应该为1";
        assert actorMetrics.getAvgPersistLatency() == 62 : "平均持久化延迟应该为62ms"; // (50+75)/2
        
        // 验证系统级别指标
        PersistenceMetricsManager.SystemMetrics systemMetrics = manager.getSystemMetrics();
        assert systemMetrics.getTotalPersistCount() == 2 : "系统持久化计数应该为2";
        assert systemMetrics.getTotalRecoveryCount() == 1 : "系统恢复计数应该为1";
        assert systemMetrics.getTotalSnapshotCount() == 1 : "系统快照计数应该为1";
        
        logger.info("✓ 性能监控管理器验证通过");
    }
    
    /**
     * 验证不同Actor类型的持久化策略
     */
    private void verifyActorTypePersistenceStrategies() {
        logger.info("验证不同Actor类型的持久化策略...");
        
        // 验证Actor状态分析
        Map<String, Integer> actorPriorities = new HashMap<>();
        actorPriorities.put("com.leon.datalink.rule.actor.RuleActor", 1);
        actorPriorities.put("com.leon.datalink.rule.actor.ScheduleNodeActor", 1);
        actorPriorities.put("com.leon.datalink.rule.actor.DriverNodeActor", 2);
        actorPriorities.put("com.leon.datalink.rule.actor.SpeedNodeActor", 2);
        actorPriorities.put("com.leon.datalink.rule.actor.PackNodeActor", 2);
        actorPriorities.put("com.leon.datalink.rule.actor.TempActor", 3);
        
        for (Map.Entry<String, Integer> entry : actorPriorities.entrySet()) {
            String actorType = entry.getKey();
            int expectedPriority = entry.getValue();
            
            int actualPriority = NodeActorStateAnalysis.getActorPersistencePriority(actorType);
            assert actualPriority == expectedPriority : 
                String.format("Actor %s 的优先级应该为 %d，实际为 %d", actorType, expectedPriority, actualPriority);
            
            String strategy = NodeActorStateAnalysis.getRecommendedPersistenceStrategy(actorType);
            assert strategy != null && !strategy.isEmpty() : "推荐策略不能为空";
            
            logger.debug("Actor类型 {} 优先级: {}, 推荐策略: {}", actorType, actualPriority, strategy);
        }
        
        logger.info("✓ Actor类型持久化策略验证通过");
    }
    
    /**
     * 验证状态变化统计
     */
    private void verifyStateChangeStatistics() {
        logger.info("验证状态变化统计...");
        
        SnapshotStrategyManager manager = SnapshotStrategyManager.getInstance();
        String actorType = "TestActor";
        String nodeId = "test-node-stats";
        
        // 创建测试状态
        NodeState oldState = createTestNodeState(nodeId);
        oldState.setProcessedCount(100);
        
        NodeState newState = createTestNodeState(nodeId);
        newState.setProcessedCount(101);
        newState.setStatus(NodeStatus.RUNNING);
        
        // 更新状态变化统计
        manager.updateStateChangeStats(actorType, nodeId, oldState, newState);
        
        // 验证快照策略是否被动态调整
        SnapshotStrategyManager.SnapshotStrategy strategy = manager.getSnapshotStrategy(actorType, nodeId);
        assert strategy != null : "快照策略不能为空";
        
        logger.info("✓ 状态变化统计验证通过");
    }
    
    /**
     * 验证性能监控和报告
     */
    private void verifyPerformanceMonitoring() {
        logger.info("验证性能监控和报告...");
        
        PersistenceMetricsManager manager = PersistenceMetricsManager.getInstance();
        
        // 模拟多个Actor的性能数据
        String[] actorTypes = {"RuleActor", "ScheduleNodeActor", "DriverNodeActor"};
        
        for (int i = 0; i < actorTypes.length; i++) {
            String actorType = actorTypes[i];
            String nodeId = "node-" + i;
            
            // 模拟不同的性能特征
            for (int j = 0; j < 10; j++) {
                long persistTime = 20 + i * 10 + j; // 不同Actor有不同的延迟特征
                long dataSize = 1024 + j * 100;
                manager.recordPersistOperation(actorType, nodeId, persistTime, dataSize);
                
                if (j % 3 == 0) {
                    manager.recordRecoveryOperation(actorType, nodeId, persistTime * 2, 1);
                }
                
                if (j % 5 == 0) {
                    manager.recordSnapshotOperation(actorType, nodeId, persistTime * 3, dataSize * 2);
                }
            }
        }
        
        // 生成性能报告
        String report = manager.generatePerformanceReport();
        assert report != null && !report.isEmpty() : "性能报告不能为空";
        assert report.contains("系统级别指标") : "报告应该包含系统级别指标";
        assert report.contains("Top 10") : "报告应该包含Top 10统计";
        
        logger.info("性能报告预览:\n{}", report);
        
        logger.info("✓ 性能监控和报告验证通过");
    }
    
    /**
     * 验证系统级别的聚合指标
     */
    private void verifySystemLevelMetrics() {
        logger.info("验证系统级别的聚合指标...");
        
        PersistenceMetricsManager manager = PersistenceMetricsManager.getInstance();
        PersistenceMetricsManager.SystemMetrics systemMetrics = manager.getSystemMetrics();
        
        // 验证聚合指标
        assert systemMetrics.getTotalPersistCount() > 0 : "系统总持久化次数应该大于0";
        assert systemMetrics.getAvgPersistLatency() > 0 : "系统平均持久化延迟应该大于0";
        assert systemMetrics.getPersistThroughput() >= 0 : "系统持久化吞吐量应该大于等于0";
        
        // 验证所有Actor指标
        Map<String, PersistenceMetricsManager.ActorMetrics> allMetrics = manager.getAllActorMetrics();
        assert !allMetrics.isEmpty() : "应该有Actor指标数据";
        
        long totalActorPersistCount = allMetrics.values().stream()
                .mapToLong(PersistenceMetricsManager.ActorMetrics::getTotalPersistCount)
                .sum();
        
        assert totalActorPersistCount == systemMetrics.getTotalPersistCount() : 
            "Actor级别的总计数应该等于系统级别的总计数";
        
        logger.info("系统级别指标: {}", systemMetrics.toString());
        logger.info("Actor数量: {}", allMetrics.size());
        
        logger.info("✓ 系统级别聚合指标验证通过");
    }
    
    /**
     * 创建测试节点状态
     */
    private NodeState createTestNodeState(String nodeId) {
        NodeState state = new NodeState();
        state.setNodeId(nodeId);
        state.setStatus(NodeStatus.STARTING);
        state.setProcessedCount(0);
        state.setLastEventTime(System.currentTimeMillis());
        
        Map<String, Object> properties = new HashMap<>();
        properties.put("test", "value");
        state.setProperties(properties);
        
        return state;
    }
}
